package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
)

const (
	user   = "root"
	pwd    = "ut123456"
	dbName = "shuogg"
)

type Teacher struct {
	Id   int64
	Name string
	Age  uint8
}

func main() {
	db := connectDB(user, pwd, dbName)
	insertTeacher(db, "Wang", 22)
	updateName(db, 17, "Dako")
	getById(db, 17)
}

func connectDB(user, pwd, dbName string) *sql.DB {
	dsn := fmt.Sprintf("%s:%s@/%s?charset=utf8", user, pwd, dbName)
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		panic(err)
	}
	return db
}

func insertTeacher(db *sql.DB, name string, age int) (newId int64) {
	stmt, err := db.Prepare(`insert into teacher(name, age) values (?, ?)`)
	res, err := stmt.Exec(name, age)
	newId, err = res.LastInsertId()
	if err != nil {
		newId = -1
	}
	return
}

func updateName(db *sql.DB, id int64, name string) {
	stmt, err := db.Prepare("update teacher set name=? where id=?")
	_, err = stmt.Exec(name, id)
	if err != nil {
	}
}

func getById(db *sql.DB, id int64) {
	rows, _ := db.Query("select * from teacher where id=?", id)
	t := new(Teacher)
	for rows.Next() {
		rows.Scan(&t.Id, &t.Name, &t.Age)
		fmt.Println(*t)
	}
}
